# -*- coding: utf-8 -*-
"""
@Time : 2024/10/17 18:13
@Author : ChenXiaoliang
@Email : middlegod@sina.com
@File : send_email.py
"""
import os
import logging
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

from sys_func.read_config import load_yaml

LOG_FORMAT = "%(levelname)s %(asctime)s - %(message)s"
logging.basicConfig(filename='monitor.log', level=logging.INFO, filemode='a', format=LOG_FORMAT)
logger = logging.getLogger()


def send_email(title, content, content_type):
    """
    发送邮件
    :param title: 邮件主题
    :param content: 邮件正文内容
    :param content_type: 邮件正文内容格式 比如 "plain" 或者 "html"
    :return:
    """
    config_data = load_yaml('config_monitor.yaml')

    # 邮件发送者和接收者
    sender_email = config_data.get('email').get('sender')
    receiver_email = ','.join(config_data.get('email').get('receiver'))
    password = os.environ.get("EMAIL_PW")

    # 创建邮件对象
    message = MIMEMultipart("alternative")
    message["Subject"] = f"{title}"
    message["From"] = sender_email
    message["To"] = receiver_email

    # 将文本内容添加到邮件中
    part = MIMEText(content, content_type)
    message.attach(part)

    # 连接到SMTP服务器并发送邮件
    try:
        server = smtplib.SMTP("smtp.qq.com", 587)  # SMTP服务器地址和端口号
        server.starttls()  # 启用TLS安全传输
        server.login(sender_email, password)  # 登录验证
        server.sendmail(sender_email, receiver_email, message.as_string())  # 发送邮件
        logger.info(f"成功发送email - {title}！")
        return True
    except Exception as e:
        logger.error(f"发送邮件失败！{title}，报错信息{e}")
    finally:
        server.quit()  # 断开服务器连接
